import { defineStore } from 'pinia'
import { loginForm } from '@/api/user/type'
import { reqLogin, reqLogout, reqUserInfo } from '@/api/user'
import { HttpStatusCode } from 'axios'
import { UserState } from '@/store/modules/types/type'
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from '@/utils/token'
import { constantRoute } from '@/router/routes'

const useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
    }
  },
  actions: {
    async userLogin(data: loginForm) {
      const result = await reqLogin(data)
      if (result.ok && result.code === HttpStatusCode.Ok) {
        this.token = result.data ? result.data : ''
        SET_TOKEN(this.token)
        return 'Ok'
      } else {
        return Promise.reject(new Error(`${result.message}: ${result.data}`))
      }
    },
    async userInfo() {
      const result = await reqUserInfo()
      if (result.ok && result.code === HttpStatusCode.Ok) {
        this.avatar = result.data.avatar
        this.username = result.data.name
        return 'Ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    async userLogout() {
      const result = await reqLogout()
      if (result.ok && result.code === HttpStatusCode.Ok) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'Ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
